package com.shu.Thread;

import com.google.common.base.Stopwatch;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class AwaitNotify {


    @Test
    public void name() throws InterruptedException {
        Stopwatch stopwatch = Stopwatch.createStarted();
        CountDownLatch startDownLatch= new CountDownLatch(50);
        CountDownLatch endDownLatch = new CountDownLatch(50);
        ExecutorService service = Executors.newFixedThreadPool(50);
        Object lock = new Object();

        Runnable notify = () -> {
            try {
//                TimeUnit.SECONDS.sleep(1);
                synchronized (lock) {
                    lock.notify();
                    System.out.println(Thread.currentThread().getName() + "----synchronized.notify----");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        Runnable wait = () -> {
            try {
//                TimeUnit.SECONDS.sleep(1);
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + "----synchronized.阻塞----");
                    startDownLatch.countDown();
                    lock.wait();
                    endDownLatch.countDown();
                    System.out.println(Thread.currentThread().getName() + "----synchronized.wait1释放----");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };


        for (int i = 0; i < 50; i++) {
            service.submit(wait);
            // service.submit(notify);
        }
        startDownLatch.await();
        synchronized (lock) {
            lock.notifyAll();
            System.out.println(Thread.currentThread().getName() + "----synchronized.notifyAll释放----");
        }

        endDownLatch.await();
        System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS)+"毫秒后执行");
    }
}
